package com.db.controller;

import com.db.common.pojo.PageObject;
import com.db.pojo.SysUser;
import com.db.service.SysUserService;
import com.db.vo.SysResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/user/")
public class SysUserController {

	@Autowired
	private SysUserService sysUserService;

	@RequestMapping("doFindPageObjects")
	public SysResult doFindPageObjects(String username, Integer pageCurrent) {
		PageObject<SysUser> sysUserPageObject = sysUserService.findObjects(username, pageCurrent);
		return new SysResult(sysUserPageObject);
	}

	@RequestMapping("doValidById")
	public SysResult doValidById(Integer id, Integer valid) {
		sysUserService.updateValid(id, valid);
		return new SysResult("update ok");
	}

	@RequestMapping("doSaveObject")
	public SysResult doSaveObject(SysUser sysUser, Integer... roleIds) {
		sysUserService.insertObject(sysUser, roleIds);
		return new SysResult("insert ok");
	}

	@RequestMapping("doFindObjectById")
	public SysResult doFindObjectById(Integer id) {
		Map<String, Object> sysUser = sysUserService.findById(id);
		return new SysResult(sysUser);
	}

	//doUpdateObject
	@RequestMapping("doUpdateObject")
	public SysResult doUpdateObject(SysUser sysUser, Integer... roleIds) {
		sysUserService.updateObject(sysUser, roleIds);
		return new SysResult("update ok");
	}

	//doLogin
	@RequestMapping("doLogin")
	public SysResult doLogin(String username, String password, Boolean isRememberMe) {
		//获取subject对象
		Subject subject = SecurityUtils.getSubject();
		//对用户名和密码进行封装
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		if (isRememberMe) {
			token.setRememberMe(true);
		}
		//将信息进行认证
		subject.login(token);
		return new SysResult("login ok");
	}

	//doUpdatePassword
	@RequestMapping("doUpdatePassword")
	public SysResult doUpdatePassword(String pwd, String newPwd, String cfgPwd) {
		sysUserService.updatePassWord(pwd, newPwd, cfgPwd);
		return new SysResult("update ok");
	}
}
